package com.q3d.demo.common.lib.ip;

import java.net.InetAddress;

import org.springframework.http.server.reactive.ServerHttpRequest;

import lombok.extern.slf4j.Slf4j;

@Slf4j /** Lombok 的 Logger 注解 */
public class IpUtilForServerHttpRequest {

    private static final String IP_UTILS_FLAG = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IPv6 = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IPv4 = "127.0.0.1";

    /**
     * 根据 HttpHeaders 获取真实 IP 的方法
     */
    public static String getRemoteIPv4(ServerHttpRequest request) {
        String ip = null;
        try {
            ip = request.getHeaders().getFirst("X-Forwarded-For");
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeaders().getFirst("x-forwarded-for");
                if (ip != null && ip.length() != 0 && !UNKNOWN.equalsIgnoreCase(ip)) {
                    // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                    if (ip.contains(IP_UTILS_FLAG)) {
                        ip = ip.split(IP_UTILS_FLAG)[0];
                    }
                }
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeaders().getFirst("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeaders().getFirst("X-Real-IP");
            }
            // 兼容k8s集群获取ip
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddress().getAddress().getHostAddress();
                if (LOCALHOST_IPv4.equalsIgnoreCase(ip) || LOCALHOST_IPv6.equalsIgnoreCase(ip)) {
                    // 根据网卡取本机配置的IP
                    InetAddress iNet = null;
                    iNet = InetAddress.getLocalHost();
                    ip = iNet.getHostAddress();
                }
            }
        } catch (Exception e) {
            log.error("GetClientIp_Failed: ", e);
        }
        // 使用代理，则获取第一个IP地址
        if (ip != null && ip.length() > 0 && ip.indexOf(IP_UTILS_FLAG) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
        }
        return ip.equals(LOCALHOST_IPv6) ? LOCALHOST_IPv4 : ip;
    }

}
